package com.ld.security.common.quartz.modules.job.job;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.ld.security.common.core.base.column.ListJson;
import com.ld.security.common.quartz.modules.job.constant.JobLogConstant;
import com.ld.security.common.quartz.modules.job.entity.JobLogEntity;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.impl.JobDetailImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

@Slf4j
public abstract class SuperJob extends QuartzJobBean {



    @Autowired
    JobLogQueue jobLogQueue;



    public abstract void run(JobExecutionContext jobExecutionContext);


        protected void addLog(JobExecutionContext jobExecutionContext,JobLogConstant.logType logType,String content){

        JobDetailImpl jobDetail = (JobDetailImpl) jobExecutionContext.getJobDetail();

        JobDataMap jobDataMap =  jobDetail.getJobDataMap();
        ListJson config = (ListJson)jobDataMap.get(JobArgs.jobConfig);
        //任务运行参数
        JobLogEntity jobLogEntity =   new JobLogEntity();
        jobLogEntity.setConfig(config);
        jobLogEntity.setLogType(logType);

        jobLogEntity.setTaskId(jobDetail.getKey().getName());
        jobLogEntity.setGroupId(jobDetail.getKey().getGroup());
        jobLogEntity.setContent(content);
        jobLogQueue.pushLog(jobLogEntity);
    }


    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        JobDetailImpl jobDetail = (JobDetailImpl) jobExecutionContext.getJobDetail();

        String name = jobDetail.getGroup()+"_"+jobDetail.getName();
        log.info(name+"定时任务执行");

        try {
           this.run(jobExecutionContext);
           this.addLog(jobExecutionContext,JobLogConstant.logType.success,"任务执行成功");
        }catch (Exception ex){
            log.error("定时任务异常",ex);
            String content = ExceptionUtil.stacktraceToString (ex);
            this.addLog(jobExecutionContext,JobLogConstant.logType.error,content);
        }

    }
}